# coding=utf-8
from selenium import webdriver
from pyquery import PyQuery as pq
import time
import json
# 配置信息
config={
    "log_QQ" :"2975679074",
    "password":"1312308948",
    "QQzerourl":"http://user.qzone.qq.com/",
    "QQnums":[
        "1312308948"
        ]
    }
def init_PhantomJS(pPath):
    service_args=[]
    service_args.append('--load-images=no')  ##关闭图片加载
    service_args.append('--disk-cache=no')  ##开启缓存
    service_args.append('--ignore-ssl-errors=true') ##忽略https错误
    driver = webdriver.PhantomJS(executable_path=pPath,service_args=service_args)
    driver.maximize_window()
    return driver

def login_QQ(driver,qqnum,password):
    # 判断是否登录页
    try :
        driver.find_element_by_id('login_div')
        a = True
    except:
        a = False
    if a==False :  # 如果不是登录页 返回login失败
        print('is not login page!')
        return False
    # 如果是登录页 开始模拟登录
    try:
        driver.switch_to.frame('login_frame')            #切换到登录ifram
        time.sleep(2)
        driver.find_element_by_id('switcher_plogin').click()
        time.sleep(2)
        driver.find_element_by_id('u').clear()           #选择用户名框
        driver.find_element_by_id('u').send_keys(qqnum)
        driver.find_element_by_id('p').clear()           #选择密码框
        driver.find_element_by_id('p').send_keys(password)
        driver.find_element_by_id('login_button').click()   #点击登录按钮
    except :
        driver.save_screenshot('./error.jpg')
        return False
    time.sleep(4)
    # 判断好友是否有权限 
    try:
        driver.find_element_by_id('QM_OwnerInfo_Icon')
        b = True
    except:
        b = False
    if b==False :
        print('not acc')
        return False
    else :
        return driver
def anaDat(htmlText):
    resDat = []
    dom = pq(htmlText)
    dom = dom("ol#msgList")
    msgList = dom('div.bgr3')
    print(msgList.length)
    for oness in msgList.items():
        oneDat = {}
        dom = pq(oness)
        oneDat['text'] = dom('div.bd').text()
        stime = dom('span.c_tx3')
        stime = stime('a').attr('title')
        oneDat['stime'] = stime
        pic = dom('div.md')
        if pic != False:
            urls =[]
            pic = pic('img')
            for one in pic.items():
                urls.append(one.attr('src'))
            oneDat['picUrl'] = urls
        resDat.append(oneDat)
    return resDat
def save_data(data,path):
    json.dump(data, open(path,'w',encoding='utf-8'), ensure_ascii=False, indent=4)
    return True
def main():
    Dr = init_PhantomJS('./phantomjs.exe') #初始化浏览器
    QQzerourl = config["QQzerourl"]+config['QQnums'][0]+'/311' 
    Dr.get(QQzerourl)
    Dr = login_QQ(Dr,config["log_QQ"],config["password"]) #登录qq
    if Dr == False : 
        print('error:cannot login QQ')
        return False 
    # 切换到说说内容框
    Dr.switch_to.frame('app_canvas_frame')
    while True :
        # 判断是否有内容
        try:
            Dr.find_element_by_css_selector("img[class=\"empty_pic_message\"]")
            break
        except :
            pass
        htmlText = Dr.page_source
        # with open('./temp.html','r',encoding="utf-8") as fp : htmlText = fp.read()    
        resDat = anaDat(htmlText)       # 分析数据
        fileP = './suosuo[qq=%s]_%d.json'%(config['QQnums'][0],time.time())
        save_data(resDat,fileP)         # 保存数据
        Dr.find_element_by_css_selector("a[class=\"c_tx\"][title=\"下一页\"]").click()
        time.sleep(5)
    Dr.close()
    Dr.quit()
        # with open('./temp1.html','w',encoding="utf-8") as fp : fp.write(htmlText) 
    # with open('./temp.html','r',encoding="utf-8") as fp : htmlText = fp.read()    

if __name__ == '__main__':
    main()